//
//  THMyJoinVC.m
//  YJB
//
//  Created by YJB on 2016/11/26.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "THMyJoinVC.h"
#import "THCpcHallCell.h"
#import "masonry.h"
#import "YJUserDefaultTool.h"
#import "YJNetworkTool.h"
#import "THCpcMyJoinModel.h"
#import "THCpcTaskPublishVC.h"
#import "THCpcMyJoinTaskDetailVC.h"
#import "YJGlobalHeader.h"

@interface THMyJoinVC ()
//@property(nonatomic,strong)UIView *headView;
@property(nonatomic,strong)NSMutableArray *tasks;
@end

@implementation THMyJoinVC
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"任务列表";
    self.tableView.rowHeight = 50;
    self.tableView.backgroundColor = kUIColorFromRGB(0xeeeeee);
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[THCpcHallCell class] forCellReuseIdentifier:cpcHallCellID];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
    //self.tableView.tableHeaderView = self.headView;
    
    @weakify(self);
    [[[NOTIFICATIONCENTER rac_addObserverForName:THUserDidDeleteCpcTaskNotification object:nil] takeUntil:self.rac_willDeallocSignal]subscribeNext:^(NSNotification *x) {
        @strongify(self);
        NSString *ID = x.userInfo[@"taskId"];
        THCpcMyJoinModel *selectTask = nil;
        for (THCpcMyJoinModel *task in _tasks)
        {
            if ([task.ID isEqualToString:ID])
            {
                selectTask = task;
                break;
            }
        }
        [_tasks removeObject:selectTask];
        [self.tableView reloadData];
    }];
}

//- (UIView *)headView
//{
//    if (_headView == nil)
//    {
//        _headView = [[UIView alloc] init];
//        _headView.backgroundColor = WHITECOLOR;
//        _headView.height = 85;
//        UILabel *label = [[UILabel alloc] init];
//        [_headView addSubview:label];
//        label.textColor = kUIColorFromRGB(0x999999);
//        label.font = FONT(14);
//        label.text = @"点击按钮发布新任务";
//        [label mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.mas_equalTo(12);
//            make.height.mas_equalTo(20);
//            make.width.mas_equalTo(200);
//            make.top.mas_equalTo(20);
//        }];
//        UIButton *btn = [[UIButton alloc] init];
//        [btn setImage:Image(@"添加按钮") forState:UIControlStateNormal];
//        btn.titleLabel.font = FONT(16);
//        [_headView addSubview:btn];
//        [btn addTarget:self action:@selector(addNewTask) forControlEvents:UIControlEventTouchUpInside];
//        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.right.mas_equalTo(-20);
//            make.height.height.mas_equalTo(50);
//            make.centerY.mas_equalTo(_headView.mas_centerY);
//        }];
//    }
//    return _headView;
//}

- (void)loadData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    params[@"action"] = @"get_involve_cpclist";
    params[@"makegold"] = @{@"username":userName,
                            @"firstrow":@"-1",
                            @"listrows":@"",
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    [YJNetworkTool postWithUrl:THURL(@"clickcpc.php") parameters:params success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        NSString *code = responseObject[@"return"][@"code"];
        if (code.integerValue == 200)
        {
            NSArray *array = responseObject[@"return"][@"data"][@"list"];
            _tasks = [THCpcMyJoinModel mj_objectArrayWithKeyValuesArray:array];
        }
        else if(code.integerValue == 500)
            [_tasks removeAllObjects];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tasks.count;
}

#pragma mark ----------------------- 表格代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    //return _tasks.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    THCpcHallCell *cell = [tableView dequeueReusableCellWithIdentifier:cpcHallCellID forIndexPath:indexPath];
    cell.myJoinModel = _tasks[indexPath.row];
    return cell;
}

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YJWeakSelf
    UITableViewRowAction *taskAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [weakSelf deleteTaskWIthIndexPath:indexPath];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
    taskAction.backgroundColor = kUIColorFromRGB(0xfa5f3c);
    UITableViewRowAction *reportAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"详情" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        THCpcMyJoinModel *model = weakSelf.tasks[indexPath.section];
        THCpcMyJoinTaskDetailVC *detailVC = [[THCpcMyJoinTaskDetailVC alloc]init];
        detailVC.taskId = model.ID;
        [weakSelf.navigationController pushViewController:detailVC animated:YES];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
    reportAction.backgroundColor = kUIColorFromRGB(0xf5a741);
    return @[taskAction,reportAction];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    THCpcMyJoinModel *model = self.tasks[indexPath.row];
    THCpcMyJoinTaskDetailVC *detailVC = [[THCpcMyJoinTaskDetailVC alloc]init];
    detailVC.taskId = model.ID;
    [self.navigationController pushViewController:detailVC animated:YES];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *headerView = [[UIView alloc]init];
//    headerView.backgroundColor = kUIColorFromRGB(0xffebe7);
//    
//    UIView *lineOne = [[UIView alloc]init];
//    lineOne.backgroundColor = kUIColorFromRGB(0xcccccc);
//    [headerView addSubview:lineOne];
//    [lineOne mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.top.mas_equalTo(0);
//        make.height.mas_equalTo(0.5);
//    }];
//    
//    UIView *lineTwo = [[UIView alloc]init];
//    lineTwo.backgroundColor = kUIColorFromRGB(0xcccccc);
//    [headerView addSubview:lineTwo];
//    [lineTwo mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.mas_equalTo(0);
//        make.height.mas_equalTo(0.5);
//    }];
//    
//    NSArray *titles = @[@"任务标题",@"点击价格",@"日期"];
//    NSArray *widths = @[@(IPHONE_W - 18 * GRIDW),@(9 * GRIDW),@( 9 * GRIDW)];
//    UILabel *lastLab = nil;
//    for (int i = 0; i < titles.count; i ++)
//    {
//        UILabel *lab = [[UILabel alloc]init];
//        lab.textColor = kUIColorFromRGB(0x333333);
//        lab.font = FONT(15);
//        lab.text = titles[i];
//        lab.textAlignment = NSTextAlignmentCenter;
//        [headerView addSubview:lab];
//        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(0.5);
//            make.bottom.mas_equalTo(-0.5);
//            make.width.equalTo(widths[i]);
//            if (lastLab)
//                make.left.mas_equalTo(lastLab.mas_right);
//            else
//                make.left.mas_equalTo(0);
//        }];
//        lastLab = lab;
//    }
//    return headerView;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return 10;
    }
    return 5;
}


- (void)addNewTask
{
    THCpcTaskPublishVC *taskVC = [[THCpcTaskPublishVC alloc]init];
    [self.navigationController pushViewController:taskVC animated:YES];
}

- (void)deleteTaskWIthIndexPath:(NSIndexPath *)indexPath
{
    THCpcMyJoinModel *model = _tasks[indexPath.row];
    [MBProgressHUD showMessage:@"正在删除" toView:self.view];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userName = [YJUserDefaultTool readUserName];
    NSString *md5Key = [YJUserDefaultTool readKeyID];
    params[@"action"] = @"del_cpc_one";
    params[@"makegold"] = @{@"username":userName,
                            @"task_id":model.ID,
                            @"user_info":userName,
                            @"phone_info":@"iOS",
                            @"md5_key":md5Key};
    [YJNetworkTool postWithUrl:THURL(@"clickcpc.php") parameters:params success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        NSString *code = responseObject[@"return"][@"code"];
        if (code.integerValue == 200)
        {
            [_tasks removeObject:model];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [NOTIFICATIONCENTER postNotificationName:THUserDidDeleteCpcTaskNotification object:nil userInfo:@{@"taskId":model.ID}];
        }
        else
        {
            NSString *message = responseObject[@"return"][@"message"];
            [MBProgressHUD showError:message toView:self.view];
        }
    } failure:^(NSError *error)
     {
         [MBProgressHUD hideHUDForView:self.view];
         [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
     }];
}

@end
